//
//  AppDelegate.m
//  yonghu
//
//  Created by 浪尖渝力 on 2018/1/12.
//  Copyright © 2018年 com.DJS. All rights reserved.
//

#import "AppDelegate.h"
#import "LogingViewController.h"
#import "HomeViewController.h"
#import "informationViewController.h"
#import "SuccessCaseViewController.h"
#import "CaseViewController.h"
#import "MyViewController.h"
#import "WXApi.h"
#import "newsViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "yinDaoYeViewController.h"
#import <AdSupport/AdSupport.h>
#define NSFoundationVersionNumber_iOS_9_x_Max
@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate>
@property(nonatomic,assign)int login;
@property(nonatomic,strong)BaseViewController *viewController;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
      
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:nil
                 apsForProduction:true
            advertisingIdentifier:advertisingId];
    
    [self getBan];
    
//    [JPUSHService setAlias:@"10" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
//        NSLog(@"%@",iAlias);
//        if (iResCode == 0) {
//            NSLog(@"添加别名成功");
//        }
//    } seq:1];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage:) name:@"login" object:nil];
    
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage2:) name:@"zhiFu" object:nil];
    
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(networkDidReceiveMessage3:) name:@"推送" object:nil];
    
    [WXApi registerApp:@"wx52f4488a00cae8e6"];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

    NSString *getAPPBanben=[ZQTools getAPPBanben];

    NSString *getAPPBanben2=[user objectForKey:@"getAPPBanben"];

    if (getAPPBanben2==nil ||! [getAPPBanben isEqualToString:getAPPBanben2]) {

        yinDaoYeViewController *yindao=[[yinDaoYeViewController alloc] init];
        UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:yindao];
        self.window.rootViewController=nav1;

    }

    else{
           
        
        HomeViewController *shouye=[[HomeViewController alloc] init];
        informationViewController *huDong=[[informationViewController alloc] init];
        CaseViewController *caseView=[[CaseViewController alloc] init];
        MyViewController *youJi=[[MyViewController alloc] init];
        SuccessCaseViewController *SuccessCase=[[SuccessCaseViewController alloc] init];
        
        UINavigationController *nav1= [[UINavigationController alloc] initWithRootViewController:shouye];
        UINavigationController *nav2= [[UINavigationController alloc] initWithRootViewController:huDong];
        UINavigationController *nav3= [[UINavigationController alloc] initWithRootViewController:SuccessCase];
        UINavigationController *nav4= [[UINavigationController alloc] initWithRootViewController:caseView];
         UINavigationController *nav5= [[UINavigationController alloc] initWithRootViewController:youJi];
        
        
        nav1.title=@"首页";
        nav2.title=@"资讯";
        nav3.title=@"案例";
        nav4.title=@"案件";
        nav5.title=@"我的";
        
        [nav1.tabBarItem setSelectedImage:[UIImage imageNamed:@"首页1"]];
        [nav1.tabBarItem setImage:[UIImage imageNamed:@"首页"]];
        
        [nav2.tabBarItem setSelectedImage:[UIImage imageNamed:@"资讯1"]];
        [nav2.tabBarItem setImage:[UIImage imageNamed:@"资讯"]];
        
        [nav3.tabBarItem setSelectedImage:[UIImage imageNamed:@"经典案例2"]];
        [nav3.tabBarItem setImage:[UIImage imageNamed:@"经典案例1"]];
        
        
        [nav4.tabBarItem setSelectedImage:[UIImage imageNamed:@"案件1"]];
        [nav4.tabBarItem setImage:[UIImage imageNamed:@"案件"]];
        
        [nav5.tabBarItem setSelectedImage:[UIImage imageNamed:@"我的1"]];
        [nav5.tabBarItem setImage:[UIImage imageNamed:@"我的"]];
        
        [[UITabBar appearance] setTintColor:_backgroundColor];
        
        UITabBarController *bar=[[UITabBarController alloc] init];
        bar.viewControllers=@[nav1,nav2,nav3,nav4,nav5];
        
        
        [[UITabBarItem appearance]setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} forState:UIControlStateNormal];
        
        self.window.rootViewController=bar;
        [self.window makeKeyAndVisible];
    }

    return YES;
}

-(void)getBan{
    NSString *banben=[ZQTools getAPPBanben];
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:banben,@"edition_num", nil];
    [ZQTools AFNPostDataUrl:@"waiter/check/is_check" Dict:dic andTableView:nil andViewController:nil andSuccessBlock:^(id responseObject) {

        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:responseObject forKey:@"isOrSH"];

    } anderrorBlock:nil];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    

    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {

    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void)networkDidReceiveMessage:(NSNotification *)notification{
    _login=1;
    
}

-(void)networkDidReceiveMessage2:(NSNotification *)notification{
    _login=2;
    
    
}
- (void)getWechatAccessTokenWithCode:(NSString *)code
{
    
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
                    @"wx52f4488a00cae8e6",@"932e607e26a11507665fe9162c71e9fa",code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSString *accessToken = dic[@"access_token"];
                NSString *openId = dic[@"openid"];
                NSLog(@"%@",accessToken);
                [self getWechatUserInfoWithAccessToken:accessToken openId:openId];
            }
        });
    });
}

- (void)getWechatUserInfoWithAccessToken:(NSString *)accessToken openId:(NSString *)openId
{
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSNotification * notice = [NSNotification notificationWithName:@"abc" object:nil userInfo:dic];
                //发送消息
                [[NSNotificationCenter defaultCenter]postNotification:notice];
            }
        });
        
    });
}

- (void)onResp:(BaseResp *)resp {
    if (_login==1) {
        _login=0;
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode== 0) {
            NSString *code = aresp.code;
            [self getWechatAccessTokenWithCode:code];
        }

    }
    else if(_login==2){
        NSString * strMsg = [NSString stringWithFormat:@"errorCode: %d",resp.errCode];
        NSLog(@"strMsg: %@",strMsg);
        
        NSString * errStr       = [NSString stringWithFormat:@"errStr: %@",resp.errStr];
        NSLog(@"errStr: %@",errStr);
        
        
        NSString * strTitle;
        //判断是微信消息的回调 --> 是支付回调回来的还是消息回调回来的.
        if ([resp isKindOfClass:[SendMessageToWXResp class]])
        {
            strTitle = [NSString stringWithFormat:@"发送媒体消息的结果"];
        }
        
        NSString * wxPayResult;
        //判断是否是微信支付回调 (注意是PayResp 而不是PayReq)
        
        if ([resp isKindOfClass:[PayResp class]])
        {
            //支付返回的结果, 实际支付结果需要去微信服务器端查询
            strTitle = [NSString stringWithFormat:@"支付结果"];
            switch (resp.errCode)
            {
                case WXSuccess:
                {
                    strMsg = @"支付结果:";
                    NSNotification * notice = [NSNotification notificationWithName:@"zhiFu2" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter]postNotification:notice];
                    break;
                }
                case WXErrCodeUserCancel:
                {
                    strMsg = @"用户取消了支付";
                    NSLog(@"用户取消支付: %d",resp.errCode);
                    wxPayResult = @"cancel";
                    [ZQTools svpInfo:@"用户取消了支付"];
                    break;
                }
                default:
                {
                    strMsg = [NSString stringWithFormat:@"支付失败! code: %d  errorStr: %@",resp.errCode,resp.errStr];
                    NSLog(@":支付失败: code: %d str: %@",resp.errCode,resp.errStr);
                    wxPayResult = @"faile";
                    [ZQTools svpInfo:@"支付失败"];
                    break;
                }
            }
            
        }
    }
 }
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    else {
        // 本地通知
    }
    
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得Extras字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段，key是自己定义的
    NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler();  // 系统要求执行这个方法
    
    NewsViewController *news=[[NewsViewController alloc] init];
    [ZQTools pushNextViewController:_viewController  andRootController:news];
    
    
}


-(void)networkDidReceiveMessage3:(NSNotification *)notification{
    
    NSLog(@"%@",notification.userInfo);
    NSDictionary *dic=notification.userInfo;
    _viewController=[dic objectForKey:@"viewController"];
}




@end
